package com.ymt.bpm.web.rest;

import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.service.dingtalk.DDMAppService;
import com.ymt.bpm.util.dingtalk.OApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * 钉钉微应用集成服务
 */
@RestController
@RequestMapping("/openapi/v1/dingtalk/mapp")
public class DDMAppResource {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private Environment env;

    @Autowired
    private DDMAppService ddmas;

    @GetMapping("testget")
    public JSONObject testget() {
        return ddmas.testget();
    }

    @GetMapping("/ddConfig")
    public JSONObject getDdConfig(HttpServletResponse response,
                                  @RequestParam("pageUrl")String pageUrl) {
        if (log.isDebugEnabled()) {
            log.debug("getDdConfig pageUrl="+pageUrl);
        }
        response.setHeader("Access-Control-Allow-Origin", env.getProperty("dingtalk.allow-origin", "*"));
        JSONObject rtn = null;
        try {
            rtn = ddmas.getDdConfig(pageUrl);
        } catch (OApiException e) {
            e.printStackTrace();
        }
        return rtn;
    }

    @GetMapping("/currentUser")
    public JSONObject getDDUserInfo(HttpServletResponse response,
                                    @RequestParam("ddAppId")String ddAppIdEnc,
                                    @RequestParam("code")String code) {
        if (log.isDebugEnabled()) {
            log.debug("currentUser ddAppIdEnc="+ddAppIdEnc);
            log.debug("currentUser　code="+code);
        }
        response.setHeader("Access-Control-Allow-Origin", env.getProperty("dingtalk.allow-origin", "*"));
        JSONObject rtn = null;
        try {
            rtn = ddmas.getDDUserInfo(ddAppIdEnc, code);
        } catch (OApiException e) {
            e.printStackTrace();
        }
        return rtn;
    }

}
